<?php
    if(basename(__FILE__) == basename($_SERVER['PHP_SELF'])){exit();}
?>
<div id="search_user_widget" class="widgetcontainer" <?php if (!isLoggedIn() || $_SESSION['User']->UserType == "Customer") echo "style=\"display:none;\""; ?>>
    <div id="search_user_heading" class="widgetheading">
        Search/Edit a User<img src="images/plus.jpg"/>
    </div>
    <div id="search_user" class="widget">
        <script type="text/javascript">
            $("#search_user_heading").data("divlink", $("#search_user"));
            $("#search_user").data("heading", $("#search_user_heading"));
            $("#search_user_heading").data("clear", function() {
                //Clear the data on user logout
                $("#user_search_query").val("");
                $("#user_search_type").val("username");
                $("#user_search_table tbody > tr").remove();
                $("#user_edit_table_body > tr").remove();
                $("#user_edit_result").text("");
                $("#user_edit_result").attr("class", "");
            });
        </script>
        <div id="clear"></div>
        <div >
            <form>
                User Search: <input id="user_search_query" style="margin-left:10px;margin-right:10px;width:200px;" name="user_search_query" type="text" />
                Search Type: <select id="user_search_type" style="margin-left:10px;margin-right:30px;"><option value="username">User Name</option><option value="id">User ID</option><option value="lastname">Last Name</option></select>
                <input type="submit" class="button blue" value="Search" onclick="doUserLookup($('#user_search_query').val(), $('#user_search_type').val());return false;"/>
            </form>
            <br />
            <b>Click on a user to edit their information.</b>
            <table id="user_search_table" class="rounded-corner sortable">
                <thead style="text-align:center;"><tr>
                    <th>User ID</th><th>User Name</th><th>User Type</th><th>First Name</th><th>Last Name</th><!--<th>Delete</th>-->
                </tr></thead>
                <tbody id="user_search_table_body">
                </tbody>
            </table>
            <hr />
            <div id="user_edit_result" style="display:none;"></div>
            <table id="user_edit_table" class="rounded-corner">
                <thead style="text-align:center;"><tr>
                    <th>User Value</th><th>Current Value</th><th>Edit</th>
                </tr></thead>
                <tbody id="user_edit_table_body">
                    
                </tbody>
            </table>
            
            <div>
            </div>
        </div>
        <br />
    </div>
    <br />
</div>
<script type="text/javascript">
    function loadEditUserTable(userid) {
        $("#user_edit_table_body > tr").remove();
        $.ajax({
            type: 'POST',
            url: '../backend/edit_user.php',
            dataType: 'json',
            data: {
                action: 'edit_load',
                uid: userid
            },
            success: function(data) {
                var resp = $("#user_edit_result");
                resp.hide();
                if (data["Success"] == 1) {
                    var any = false;
                    $.each(data["Properties"], function(key, value) {
                        any = true;
                        var tr = $("<tr>");
//                        tr.bind("click", function() {
//                            //loadEditUserTable($($(this).find("td")[0]).text());
//                        });
                        tr.append($("<td>").text(value[1]));
                        tr.append($("<td>").text(value[2]));
                        tr.append($("<td>").html("<form id='edit_user_"+value[0]+"' action='' onSubmit='return false;'><input style='margin-right:20px;' type='text' /><input type='hidden' value='"+userid+"' /><input type='hidden' value='"+value[0]+"' /><input id='edit_user_"+value[0]+"_button' type='submit' class='button small blue' value='Change'/></form>"));
                        
                        
                        $("#user_edit_table_body").append(tr);
                    });
                    $("#user_edit_table_body form").submit(function (e) {
                        var val = e.currentTarget.children[0].value;
                        //tes = e;
                        //alert();
                        if (val == "") {
                            resp.attr("class", "error");
                            resp.text("Please enter a value.");
                            resp.show();
                        } else {
                            $.ajax({
                                type: 'POST',
                                url: '../backend/edit_user.php',
                                dataType: 'json',
                                data: {
                                    action: 'edit',
                                    f: $($(e.currentTarget.parentNode.parentNode).find("td")[2]).find("input")[2].value,
                                    d: val,
                                    uid: $($(e.currentTarget.parentNode.parentNode).find("td")[2]).find("input")[1].value
                                },
                                success: function(data) {
                                    if (data["Success"] == 1) {
                                        resp.attr("class", "success");
                                        resp.text("Value changed successfully.");
                                        if ($($(e.currentTarget.parentNode.parentNode).find("td")[0]).text() != "Password")
                                            $($(e.currentTarget.parentNode.parentNode).find("td")[1]).text(val);
                                        resp.show();
                                    } else {
                                        resp.attr("class", "error");
                                        resp.text(data["Msg"]);
                                        resp.show();
                                    }
                                }
                            });
                        }
                        e.preventDefault();
                    });
                    if (!any) {
                        var tr = $("<tr>");
                        tr.append($("<td colspan='3'>").text(data["Msg"]));
                        $("#user_edit_table_body").append(tr);
                    } else {
                        var tr = $("<tr class='hilite'>");
                        tr.append($("<td>").text("Type 'Confirm' to delete."));
                        tr.append($("<td>").html("<input id='del_user_confirm' type='text'/><input type='hidden' value='"+userid+"'/>"));
                        tr.append($("<td>").html("<button id='del_user_button' type='button' class='button small blue'>Delete</button>"));
                        $("#user_edit_table_body").append(tr);
                        
                        $("#del_user_button").click( function(e2) {
                            resp.hide();
                            //asd = e2;
                            if ($("#del_user_confirm").val() == 'Confirm') {
                                $.ajax({
                                    type: 'POST',
                                    url: '../backend/edit_user.php',
                                    dataType: 'json',
                                    data: {
                                        action: 'delete',
                                        uid: e2.currentTarget.parentElement.parentElement.childNodes[1].childNodes[1].value
                                    },
                                    success: function(data) {
                                        if (data["Success"] == 1) {
                                            resp.attr("class", "success");
                                            resp.text("User Deleted successfully.");
                                            resp.show();
                                            $("#user_edit_table_body").empty();
                                            $.each($("#user_search_table_body  tr :first-child"),
                                                function() {
                                                    if ($(this).text() == e2.currentTarget.parentElement.parentElement.childNodes[1].childNodes[1].value) {
                                                        $(this).parent().remove();
                                                    }
                                                }
                                            );
                                        } else {
                                            resp.attr("class", "error");
                                            resp.text(data["Msg"]);
                                            resp.show();
                                        }
                                    }
                                });
                            } else {
                                resp.attr("class", "error");
                                resp.text("Please type confirm to delete this user.");
                                resp.show();
                            }
                        });
                    }
                } else {
                    var tr = $("<tr>");
                    tr.append($("<td colspan='3'>").text(data["Msg"]));
                    $("#user_edit_table_body").append(tr);
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
            }
        });
        
    }
    function doUserLookup(query, type) {
        if (query == "") {
            $("#user_search_table tbody > tr").remove();
            var tr = $("<tr>");
            tr.append($("<td colspan='5'>").text("Please enter a search query!"));
            $("#user_search_table_body").append(tr);
            return;
        }
        $.ajax({
            type: 'POST',
            url: '../backend/user_lookup.php',
            dataType: 'json',
            data: {
                t: type,
                d: query
            },
            success: function(data) {
                $("#user_search_table tbody > tr").remove();
                $("#user_edit_table_body > tr").remove(); //Clear the bottom just in case
                var any = false;
                $.each(data, function(key, value) {
                    any = true;
                    var tr = $("<tr>");
                    tr.bind("click", function() {
                        loadEditUserTable($($(this).find("td")[0]).text());
                    });
                    tr.append($("<td>").text(value["UserID"]));
                    tr.append($("<td>").text(value["UserName"]));
                    tr.append($("<td>").text(value["UserType"]));
                    tr.append($("<td>").text(value["FirstName"]));
                    tr.append($("<td>").text(value["LastName"]));
                    
                    $("#user_search_table_body").append(tr);
                });
                if (!any) {
                    var tr = $("<tr>");
                    tr.append($("<td colspan='5'>").text("No users found!"));
                    $("#user_search_table_body").append(tr);
                }
            },                    
            error: function(XMLHttpRequest, textStatus, errorThrown) {
            }
        });
    }
</script>
